package com.songtai.action.admin.product;

import java.io.File;
import java.io.PrintWriter;
import java.util.Date;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.struts2.ServletActionContext;

import com.songtai.action.SongtaiActionSupport;
import com.songtai.po.PhotoObj;
import com.songtai.service.ImageService;
import com.songtai.util.CommenUtil;
import com.songtai.util.Constants;
import com.songtai.util.DateUtils;
import com.songtai.util.Pager;

/**
 * @author 赵中杨
 * @email zhaozhongyang717@gmail.com
 * @date 2010 2010-4-20 下午02:22:59
 */
public class ImageAction extends SongtaiActionSupport {
	private static final long serialVersionUID = 1L;
	// 日志
	private static final String FILE_SAVE_DIR = "file.saveDir";
	private static final String FILE_CONFIG_NAME = "fileupload";
	private static final String CONTENT_TYPE = "text/html; charset=utf-8";
	private File uploadimg;
	private String uploadimgFileName;
	private String uploadimgContentType;
	// 图片说明
	private String elseContent;
	// 图片标题
	private String title;
	// 图片类型
	private String type;
	// 节点ID
	private Long nodeid;
	private ImageService imageService;
	// 列表
	private Pager<PhotoObj> images;
	// 当前页
	private int currentPage;
	// 产品ID
	private String pid;
	//图片
	private PhotoObj image;
	
	private String temp;
	private String method;
	private String name;

	/**
	 * 获取全部
	 * 
	 * @return
	 * @throws Exception
	 */
	public String getSomeImage() throws Exception {
		if (nodeid<1) {
			return null;
		}
		if (currentPage < 1) {
			currentPage = 1;
		}
		if(CommenUtil.isEmpty(type)){
			type = PhotoObj.TYPE_CASE;
		}
		//images = imageService.getImage(nodeid, currentPage, Constants.DEFAULT_PAGESIEZE);
		images = imageService.getAllImage(currentPage, Constants.DEFAULT_PAGESIEZE, type, nodeid);
		return SUCCESS;
	}
	
	/**
	 * 按ID获取图片
	 * @return
	 * @throws Exception
	 */
	public String getImageById() throws Exception{
		image = imageService.getImageById(pid);
		return SUCCESS;
	}
	/**
	 * 删除
	 * 
	 * @return
	 * @throws Exception
	 */
	public String deleteImage() throws Exception {
		response.setContentType(CONTENT_TYPE);
		PrintWriter out = response.getWriter();
		if (CommenUtil.isEmpty(pid)) {
			out.print("fail");
			return null;
		}
		PhotoObj pro = imageService.getImageById(pid);
		// 获取文件配置
		ResourceBundle rb = ResourceBundle.getBundle(FILE_CONFIG_NAME);
		// 获取文件上传保存路径配置
		String saveDir = rb.getString(FILE_SAVE_DIR);
		// 获取保存路径
		String uploadDir = ServletActionContext.getServletContext().getRealPath(saveDir);
		String src = pro.getPath().substring(pro.getPath().lastIndexOf("/"));
		imageService.deleteImage(pid);
		File delFile = new File(uploadDir + src);
		if (delFile.exists()) {
			delFile.delete();
		}
		out.print("success");
		return null;
	}

	/**
	 * 增加
	 * 
	 * @return
	 * @throws Exception
	 */
	public String addImage() throws Exception {
		try {
			if (uploadimg == null || uploadimgFileName == null || uploadimgContentType == null) {
				addFieldError("uploadimg", getText("update.file.error"));
				return INPUT;
			}
			if (CommenUtil.isEmpty(title) || title.length() > 40) {
				addFieldError("title", getText("title.error"));
				return INPUT;
			}
			if(CommenUtil.isEmpty(elseContent)){
				addFieldError("elseContent", getText("content.null.error"));
				return INPUT;
			}
			
			if (CommenUtil.isEmpty(type)) {
				type = PhotoObj.TYPE_CASE;
			}
			// 获取文件配置
			ResourceBundle rb = ResourceBundle.getBundle(FILE_CONFIG_NAME);
			// 获取文件上传保存路径配置
			String saveDir = rb.getString(FILE_SAVE_DIR);
			// 获取保存路径
			String uploadDir = ServletActionContext.getServletContext().getRealPath(saveDir);
			// 创建路径
			File directory = new File(uploadDir);
			// 临时文件名称
			String tmpUploadimgFileName = DateUtils.getDateString(new Date(), Constants.DATEFORMAT_YYYY_MM_DD_HH_MM_SS_NO_SEPARATOR);
			// 重新设置文件名称
			uploadimgFileName = tmpUploadimgFileName + uploadimgFileName.substring(uploadimgFileName.indexOf("."));
			// 路径不存在时
			if (!directory.exists()) {
				// 创建不存在路径
				directory.mkdirs();
			}
			// 新建需要保存的新文件
			File dest = new File(uploadDir + "/" + uploadimgFileName);
			// 将上传文件保存至配置路径
			uploadimg.renameTo(dest);
			// 得到圖片路徑
			String path = saveDir + "/" + uploadimgFileName;
			PhotoObj product = new PhotoObj();
			product.setPath(path);
			product.setElseContent(elseContent);
			product.setTitle(title);
			product.setType(type);
			product.setNid(nodeid);
			product.setReMark(temp);
			product.setName(name);
			imageService.addImage(product);
			method = SUCCESS;
			addFieldError("title", getText("add.success"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	/**
	 * 更新图片(不允许更换图片..只允许修改文字)
	 * @return
	 * @throws Exception
	 */
	public String  updateImage() throws Exception{
		if(CommenUtil.isEmpty(image.getId())){
			addActionError(getText("sys.error"));
			return INPUT;
		}
		if(CommenUtil.isEmpty(image.getTitle())||CommenUtil.isEmpty(image.getElseContent())){
			addActionError(getText("input.error"));
			return INPUT;
		}
		PhotoObj obj = new  PhotoObj();
		obj.setElseContent(image.getElseContent());
		obj.setTitle(image.getTitle());
		obj.setReMark(image.getReMark());
		obj.setId(image.getId());
		obj.setName(image.getName());
		imageService.updateImage(obj);
		addActionError(getText("update.success"));
		return SUCCESS;
	}
	
	
	@Override
	public void addActionError(String anErrorMessage) {
		// 这里要先判断一下，是我们要替换的错误，才处理
		if (anErrorMessage.startsWith("the request was rejected because its size")) {
			// 这些只是将原信息中的文件大小提取出来。
			Matcher m = Pattern.compile("\\d+").matcher(anErrorMessage);
			String s1 = "";
			if (m.find())
				s1 = m.group();
			String s2 = "";
			if (m.find())
				s2 = m.group();
			// 偷梁换柱，将信息替换掉
			super.addActionError("你上传的文件（" + s1 + "）超过允许的大小（" + s2 + "）");
		} else {// 不是则不管它
			super.addActionError(anErrorMessage);
		}
	}

	/**
	 * @return the pid
	 */
	public String getPid() {
		return pid;
	}

	/**
	 * @param pid
	 *            the pid to set
	 */
	public void setPid(String pid) {
		this.pid = pid;
	}

	/**
	 * @return the uploadimg
	 */
	public File getUploadimg() {
		return uploadimg;
	}

	/**
	 * @param uploadimg
	 *            the uploadimg to set
	 */
	public void setUploadimg(File uploadimg) {
		this.uploadimg = uploadimg;
	}

	/**
	 * @return the uploadimgFileName
	 */
	public String getUploadimgFileName() {
		return uploadimgFileName;
	}

	/**
	 * @param uploadimgFileName
	 *            the uploadimgFileName to set
	 */
	public void setUploadimgFileName(String uploadimgFileName) {
		this.uploadimgFileName = uploadimgFileName;
	}

	/**
	 * @return the uploadimgContentType
	 */
	public String getUploadimgContentType() {
		return uploadimgContentType;
	}

	/**
	 * @param uploadimgContentType
	 *            the uploadimgContentType to set
	 */
	public void setUploadimgContentType(String uploadimgContentType) {
		this.uploadimgContentType = uploadimgContentType;
	}

	

	/**
	 * @return the elseContent
	 */
	public String getElseContent() {
		return elseContent;
	}

	/**
	 * @param elseContent the elseContent to set
	 */
	public void setElseContent(String elseContent) {
		this.elseContent = elseContent;
	}

	/**
	 * @return the title
	 */
	public String getTitle() {
		return title;
	}

	/**
	 * @param title the title to set
	 */
	public void setTitle(String title) {
		this.title = title;
	}

	/**
	 * @return the type
	 */
	public String getType() {
		return type;
	}

	/**
	 * @param type
	 *            the type to set
	 */
	public void setType(String type) {
		this.type = type;
	}


	/**
	 * @return the nodeid
	 */
	public Long getNodeid() {
		return nodeid;
	}

	/**
	 * @param nodeid the nodeid to set
	 */
	public void setNodeid(Long nodeid) {
		this.nodeid = nodeid;
	}

	/**
	 * @return the imageService
	 */
	public ImageService getImageService() {
		return imageService;
	}

	/**
	 * @param imageService
	 *            the imageService to set
	 */
	public void setImageService(ImageService imageService) {
		this.imageService = imageService;
	}

	

	

	/**
	 * @return the images
	 */
	public Pager<PhotoObj> getImages() {
		return images;
	}

	/**
	 * @param images the images to set
	 */
	public void setImages(Pager<PhotoObj> images) {
		this.images = images;
	}

	/**
	 * @return the currentPage
	 */
	public int getCurrentPage() {
		return currentPage;
	}

	/**
	 * @param currentPage
	 *            the currentPage to set
	 */
	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	/**
	 * @return the method
	 */
	public String getMethod() {
		return method;
	}

	/**
	 * @param method
	 *            the method to set
	 */
	public void setMethod(String method) {
		this.method = method;
	}

	/**
	 * @param image the image to set
	 */
	public void setImage(PhotoObj image) {
		this.image = image;
	}

	/**
	 * @return the image
	 */
	public PhotoObj getImage() {
		return image;
	}

	/**
	 * @return the temp
	 */
	public String getTemp() {
		return temp;
	}

	/**
	 * @param temp the temp to set
	 */
	public void setTemp(String temp) {
		this.temp = temp;
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

}
